package com.example.idholder;

import com.example.idholder.jdbc.JdbcOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author fanhang
 */
public class DefaultIdHolder implements IdHolder {
    private static final Logger log = LoggerFactory.getLogger(DefaultIdHolder.class);

    private final JdbcOperation jdbcOperation;
    private final String holdKey;
    private final int holdId;

    public DefaultIdHolder(JdbcOperation jdbcOperation, String holdKey) {
        this.jdbcOperation = jdbcOperation;
        this.holdKey = holdKey;
        this.holdId = jdbcOperation.lock(holdKey);
    }

    @Override
    public int current() {
        return this.holdId;
    }

    @Override
    public void refresh() {
        log.info("refresh [{}] with holdKey [{}]", this.holdId, this.holdKey);
        try {
            int result = jdbcOperation.refresh(this.holdId, this.holdKey);
            if (result == 1) {
                return;
            }
            log.warn("刷新失败: {}", result);
        } catch (Exception e) {
            log.warn("刷新异常: {}", e.getMessage());
        }
    }

    @Override
    public void run() {
        this.refresh();
    }
}
